﻿using HZYProject.Core.Repositories;
using HZYProject.Domain;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HZYProject.Service.QuestionServices
{
    public class QuestionService: IQuestionService
    {
        private readonly IRepository<Question, Guid> _repository;

        public QuestionService(IRepository<Question, Guid> repository)
        {
            _repository = repository;
        }

        public async Task<PagedResultDto<Question>> GetPaginatedResult(GetQuestionInput input)
        {
            var query = _repository.GetAll();
            //搜索
            if (!string.IsNullOrEmpty(input.Title))
            {
                query = query.Where(x => x.Title.Contains(input.Title));
            }
            if (!(input.CID == Guid.Empty))
            {
                query = query.Where(x => x.ChapterID == input.CID);
            }
            if (!(input.CourseID == Guid.Empty))
            {
                query = query.Where(x => x.CourseID == input.CourseID);
            }
            //统计查询数据的总条数，用于分页计算总页数
            var count = query.Count();
            //表连接
            query = query.Include("Chapter").Include("Course");
            //根据需求进行排序，然后进行分页逻辑的计算
            query = query.OrderByDescending(x => x.TypeName).Skip((input.CurrentPage - 1) * input.MaxResultCount).Take(input.MaxResultCount);
            //将查询结果转换为List集合，加载到内存中
            var models = await query.AsNoTracking().ToListAsync();
            var dtos = new PagedResultDto<Question>
            {
                TotalCount = count,
                CurrentPage = input.CurrentPage,
                MaxResultCount = input.MaxResultCount,
                Data = models,
                FilterText = input.FilterText,
            };
            return dtos;
        }

    }
}
